import React, { PureComponent } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableWithoutFeedback,
  TouchableNativeFeedback,
  Modal,
  ScrollView,
  DeviceEventEmitter,
  TouchableOpacity,
  Image,
  Dimensions,
} from 'react-native';
import ZlstIcon from './zlst-icons';
import SearchPartBar from './search-part-bar';
import * as changePartRequest from '../services/changePart';
import Theme from '../native-base-theme/variables/commonColor';

const deviceWidth = Dimensions.get('window').width;
class SelectMaterialPosition extends PureComponent {
  mlistData = [];

  constructor(props) {
    super(props);
    this.state = {
      selectedList: [], // 已选列表
      listData: [], // 待选列表
    };
  }

  back = () => {
    if (this.props.hide) {
      this.props.hide();
    }
  }

  getLine = (num) => {
    let line = '';
    for (let i = 0; i < num; i += 1) {
      line += '\t';
    }

    return line;
  }

  // 展示以选择的故障位置
  _getSelectList = () => {
    const list = [];
    for (let i = 0, len = this.state.selectedList.length; i < len; i += 1) {
      const item = this.state.selectedList[i];
      list.push(
        <TouchableOpacity
          onPress={() => this._selectPart(item)}
          key={i}
          style={styles.selectItem}
        >
          <View>
            <Text style={{ color: '#ffffff', fontSize: 16 }}>
              {/* {`${item.splitCode} ${item.materialName || ''}`} */}
              {this.getLine(i)}
              {`${item.splitDesc}`}
            </Text>
          </View>
        </TouchableOpacity>,
      );
    }
    if (!list.length) {
      return (
        <View>
          <Text style={{ color: '#ffffff', fontSize: 16, textAlign: 'center' }}>
            暂无选择数据
          </Text>
        </View>
      );
    }
    return list;
  }

  _search = (a) => {
    const list = this.mlistData.filter((it) => (it.splitDesc.indexOf(a) !== -1));
    this.setState({ listData: list });
  }

  // 展示当前层级下带选择的故障位置
  _getList = () => {
    const list = [];
    if (this.mlistData.length) {
      list.push(<SearchPartBar placeholder={this.props.searchPlaceholder} search={this._search} />);
    }

    if (this.state.listData.length) {
      // list.push(<SearchPartBar placeholder={this.props.searchPlaceholder} search={this._search} />);
      list.push(
        <TouchableOpacity
          key="noSelect"
          onPress={this._finishSelect}
          style={styles.selectItem}
        >
          <Text style={{ color: '#4465e1', fontSize: 16 }}>
            暂不选
          </Text>
        </TouchableOpacity>,
      );
    } else {
      list.push(
        <View>
          <Text style={{ color: '#ffffff', fontSize: 16, textAlign: 'center' }}>
            暂无可选数据
          </Text>
        </View>,
      );
    }
    for (let i = 0, len = this.state.listData.length; i < len; i += 1) {
      const item = this.state.listData[i];
      list.push(
        <TouchableOpacity
          onPress={() => this._selectPart(item)}
          key={i}
          style={styles.selectItem}
        >
          <Text style={{ color: '#ffffff', fontSize: 16 }}>
            {/* {`${item.description} ${item.materialName || ''}`} */}
            {`${item.splitDesc}`}
          </Text>
        </TouchableOpacity>,
      );
    }
    return list;
  }

  _selectPart = (item) => {
    const selectedList = [];
    for (let i = 0, len = this.state.selectedList.length; i < len; i += 1) {
      if (this.state.selectedList[i].splitItemId === item.splitItemId) {
        break;
      }
      selectedList.push(this.state.selectedList[i]);
    }
    const mItem = {
      splitItemId: item.splitItemId,
      splitDesc: item.splitDesc,
      splitCode: item.splitCode,
      materialCode: item.materialCode,
      materialId: item.materialId,
      materialName: item.materialName,
      materialSpecModel: item.materialSpecModel,
    };
    selectedList.push(mItem);
    this.setState({
      selectedList,
    });
    this.getOtherSelectList(item.splitCode);
  }

  initSelect = async () => {
    // try {
    //   DeviceEventEmitter.emit('showLoading', true);
    //   const { equTypeId } = this.props;
    //   const resp = await request.getFirstLevePart(equTypeId);
    //   DeviceEventEmitter.emit('showLoading', false);
    //   if (resp.data) {
    //     this.mlistData = resp.data;
    //     this.setState({
    //       listData: resp.data,
    //     });
    //   }
    // } catch (error) {
    //   DeviceEventEmitter.emit('showLoading', false);
    //   console.log('get data error', error);
    // }

    const { splitItem } = this.props;
    // {splitItemId: '', description: ''}
    this._selectPart(splitItem);
  }

  getOtherSelectList = async (splitCode) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      // const { selectedId } = this.state;
      const resp = await changePartRequest.queryChildSplits({ splitCode });
      DeviceEventEmitter.emit('showLoading', false);
      if (resp.data) {
        this.mlistData = resp.data;
        this.setState({
          listData: resp.data,
        });

        if (resp.data.length == 0) { // 点击的节点查出来的子节点为空，说明是叶子节点
          this._finishSelect(); // 结束选择
        }
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      console.log('get data error', error);
    }
  }

  _finishSelect = () => {
    this.props.hide();
    this.props.finish(this.state.selectedList);
  }

  render() {
    const { show, hide } = this.props;
    return (
      <Modal
        visible={show}
        animationType="none"
        transparent={false}
        onRequestClose={hide}
        style={styles.pageContanier}
        onShow={this.initSelect}
      >
        <View style={styles.header}>
          <TouchableWithoutFeedback onPress={this.back}>
            <View style={{ padding: 5 }}>
              <ZlstIcon
                style={styles.backIcon}
                name="fanhui"
                size={20}
                color={fontColor}
              />
            </View>
          </TouchableWithoutFeedback>
          <Text style={styles.headerText}>请选择故障位置</Text>
          <View style={styles.rightOperate} />
        </View>
        <View style={styles.selected}>
          <View style={styles.blockTitle}>
            <Text style={{ fontSize: 16 }}>已选择位置</Text>
          </View>
          <ScrollView style={styles.content}>
            {this._getSelectList()}
          </ScrollView>
        </View>
        <View style={styles.listContent}>
          <View style={styles.blockTitle}>
            <Text style={{ fontSize: 16 }}>待选择位置</Text>
          </View>
          <ScrollView style={styles.content}>
            {this._getList()}
          </ScrollView>
        </View>
        {/* <TouchableNativeFeedback
          onPress={this._finishSelect}
        >
          <View
            style={{ backgroundColor: Theme.myPrimary }}
          >
            <Image
              source={require('../../assets/images/btn-cut-line-xxx.png')}
              style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
              resizeMode="contain"
              resizeMethod="auto"
            />
            <Text style={{
              textAlign: 'center',
              color: '#ffffff',
              paddingTop: 15,
              paddingBottom: 15,
            }}
            >
              确认
            </Text>
          </View>
        </TouchableNativeFeedback> */}
      </Modal>
    );
  }
}

const fontColor = '#ffffff';

const styles = StyleSheet.create({
  pageContanier: {
    flex: 1,
    width: '100%',
    height: '100%',
    backgroundColor: Theme.myPrimary,
  },
  header: {
    height: 40,
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: Theme.myPrimary,
  },
  headerText: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#ffffff',
  },
  selected: {
    maxHeight: '50%',
    backgroundColor: Theme.myPrimary,
  },
  listContent: {
    flex: 1,
    backgroundColor: Theme.myPrimary,
  },
  selectItem: {
    padding: 4,
  },
  blockTitle: {
    backgroundColor: '#ffffff',
    borderLeftWidth: 8,
    borderLeftColor: '#4f6fe3',
    borderStyle: 'solid',
    padding: 10,
    fontSize: 17,
  },
  content: {
    paddingTop: 5,
    paddingBottom: 5,
    paddingLeft: 15,
    paddingRight: 15,
  },
});

export default SelectMaterialPosition;
